package com.vb.ecm.web.custom.importcontent;

import com.documentum.web.common.WrapperRuntimeException;
import com.documentum.web.form.Form;
import com.documentum.web.formext.component.Component;
import java.io.IOException;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.log4j.Logger;

public class RedirectDispatcher extends HttpServlet
{

	private static final Logger LOGGER = Logger.getLogger(RedirectDispatcher.class);
    public RedirectDispatcher()
    {
    }

    @Override
	public final void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        mapRequestToDrl(req, res);
    }

    @Override
	public final void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        mapRequestToDrl(req, res);
    }

    private void mapRequestToDrl(HttpServletRequest req, HttpServletResponse res)
    {
    	LOGGER.debug("in Redirect Dispatcher===");
        StringBuffer buf = new StringBuffer(256);
        buf.append(Form.makeFullUrl(req, Form.makeUrl(req, "/redirect.html")));
        String strPathInfo = req.getPathInfo();
        StringTokenizer tokenizer = new StringTokenizer(strPathInfo, "/");
        int nArguments = 0;
        String strArgumentValue;
        for(; tokenizer.hasMoreTokens(); buf.append(strArgumentValue))
        {
            String strArgumentName = tokenizer.nextToken();
            strArgumentValue = "";
            if(tokenizer.hasMoreTokens())
            {
                strArgumentValue = tokenizer.nextToken();
            }
            nArguments++;
            buf.append(nArguments != 1 ? '&' : '?');
            buf.append(strArgumentName);
            buf.append('=');
        }

        if(nArguments > 0)
        {
            String strDrlUrl = buf.toString();
            try
            {
                res.sendRedirect(strDrlUrl);
            }
            catch(IOException e)
            {
                throw new WrapperRuntimeException((new StringBuilder()).append("RedirectDispatcher: Failed to redirect to: ").append(strDrlUrl).toString(), e);
            }
        }
    }
}

